package com.ocm.core.domain;

import java.util.ArrayList;
import java.util.List;

import com.ocm.core.exception.ExceptionCode;
import com.ocm.core.exception.TypeCodeException;
import com.ocm.core.exception.UnsupportTypeException;

public enum ParticipantType {
   HASUSER(1), HASGROUP(2), HASCREATOR(4), HASANONYMOUS(8);

   private int participantType;

   public int getParticipantType() {
      return this.participantType;
   }

   private ParticipantType(int participantType) {
      this.participantType = participantType;
   }

   public static ParticipantType getParticipantType(int type) throws UnsupportTypeException {
      ParticipantType value = null;
      switch (type) {
         case 1:
            value = ParticipantType.HASUSER;
            break;
         case 2:
            value = ParticipantType.HASGROUP;
            break;
         case 4:
            value = ParticipantType.HASCREATOR;
            break;
         case 8:
            value = ParticipantType.HASANONYMOUS;
            break;
         default:
            throw new UnsupportTypeException(ExceptionCode.instance(TypeCodeException.class,
                  TypeCodeException.PARTICIPANTTYPE));
      }
      return value;
   }

   public static ParticipantType[] getParticipantTypes(int access) throws UnsupportTypeException {
      List<ParticipantType> pers = new ArrayList<ParticipantType>();
      for (int bit = 0; bit < 7; ++bit)
      {
        int mask = 1 << bit;
        if ((access & mask) == 0)
          continue;
        pers.add(pers.size(), getParticipantType(mask));
      }
      ParticipantType[] participantTypes = pers.toArray(new ParticipantType[]{});
      return participantTypes;
   }

   public static int getAccessMask(ParticipantType... participantTypes) throws UnsupportTypeException {
      int accessMask = 0;
      for (ParticipantType participantType : participantTypes){
         accessMask += participantType.getParticipantType();
      }
      return accessMask;
   }
}
